<?php
/**
 * Created by PhpStorm.
 * User: 张良
 * Date: 2018/1/18
 * Time: 15:32
 */

namespace App\Http\Controllers\User;

use App\Http\Controllers\CommonController;
use App\Models\Files;
use App\Models\FirstType;
use App\Models\Operation;
use App\Models\Product;
use App\Models\Progress;
use App\Models\ProgressList;
use App\Models\ProgressOperatorRelation;
use App\Models\User;
use DB;
use Excel;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Request;
class MineController extends CommonController
{
    protected $pageNum = 15;
    protected $second_type_table = "second_type";
    protected $product_table = "product";
    protected $patent = 1;
    protected $trademark = 2;
    protected $copyright = 3;
    protected $project = 4;

    /**
     * 我的专利列表页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function myPatent()
    {
        $uid = Session::get('uid');
        $patent = Product::with(['Progress' => function ($query) {
            $query->orderBy('created_at', 'ASC');
        }, 'SecondType', 'FirstType','Files'])
            ->where(['user_id' => $uid])
            ->where(['first_type_id' => $this->patent])
            ->paginate($this->pageNum);
         // dd($patent);
        // collect()
        /*  $patent = object_to_array(
              DB::table('product')->
              where(array("product.user_id" => $uid, 'product.first_type_id' => 1))->
              join('second_type', 'product.second_type_id', '=', 'second_type.id')->
              leftJoin('progress', 'product.id', '=', 'progress.product_id')->
              leftJoin('progress_list', 'progress.progress_list_id', '=', 'progress_list.id')->
              get(['product.id', 'product.applicant', 'second_type.name as second_type',
                  'product.number', 'product.name', 'product.registration_time',
                  'product.authority_time', 'product.inventor', 'product.agent',
                  'progress_list.name as progress_type', 'product.file',
                  'progress.id as pid','progress.claim_state','progress.is_cancel',
                  'product.is_download_notice'
              ])
          );*/
        $second_type = object_to_array(
            DB::table('second_type')->where(array("first_type_id" => $this->patent))->
            get(['id', 'name'])
        );//获取second_type中first_type_id=1的id和name
        $progress = $this->getProgress($this->patent);//pantent=1
        //dd($progress);
        /*$data = [
            'patent' => $patent,
            'second_type' => $second_type
        ];*/
        $count = [0, 0, 0];
        $count[0]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 1],//查询link_second_type=1发明的个数
            ])->count();
        $count[1]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 2],//查询link_second_type2实用新型的个数
            ])->count();
        $count[2]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 3],//查询link_second_type=3外观设计的个数
            ])->count();
//        dd($count);
        $data = ['patent', 'second_type', 'progress','count',];
        // dump($patent);
//         dump($progress);
//
//         exit();
        return view('user/mine/myPatent', compact($data));
    }
//
//    public function myPatentSearch()
//    {
//        $uid = Session::get('uid');
//        $request = Request::all();
//        $keywords="";
//        if (isset($request['search'])) {
//            $keywords = $request['search'];
//        }
//        $patent = Product::with(['Progress' => function ($query) {
//            $query->orderBy('created_at', 'ASC');
//        }, 'SecondType', 'FirstType','Files'])
//            ->where(['user_id' => $uid])
//            ->where(['first_type_id' => $this->patent])
//            ->paginate(0);
//        $second_type = object_to_array(
//            DB::table('second_type')->where(array("first_type_id" => $this->patent))->
//            get(['id', 'name'])
//        );
//        $progress = $this->getProgress($this->patent);
//        $data = ['patent', 'second_type', 'progress','keywords'];
//        return view('user/mine/myPatentSearch', compact($data));
//    }

    public function myPatentCertain()
    {
        $uid = Session::get('uid');
        $applicant = Request::input('applicant');
        $company = Request::input('company');
        $second_type = Request::input('second_type');
        $number = Request::input('number');
        $product_name = Request::input('product_name');
        $created_at = Request::input('created_at');
        $authority_time = Request::input('authority_time');
        $inventor = Request::input('inventor');
//        dd($applicant);
        $patent = Product::with(['Progress' => function ($query) {
            $query->orderBy('created_at', 'ASC');
        }, 'SecondType', 'FirstType','Files'])
            ->where([
                ['user_id','=',$uid],
                ['first_type_id','=',$this->patent],
            ])
            ->when($applicant, function ($query) use ($applicant) {
                return $query->where('product.applicant', $applicant);
            })
            ->when($company, function ($query) use ($company) {
                return $query->where('product.company', $company);
            })
            ->when($second_type, function ($query) use ($second_type) {
                return $query->where('product.second_type_id', $second_type);
            })
            ->when($number, function ($query) use ($number) {
                return $query->where('product.number', $number);
            })
            ->when($product_name, function ($query) use ($product_name) {
                return $query->where('product.name', $product_name);
            })
            ->when($created_at, function ($query) use ($created_at) {
                return $query->where('product.created_at','like', '%'.$created_at.'%');
            })
            ->when($authority_time, function ($query) use ($authority_time) {
                return $query->where('product.authority_time','like', '%'.$authority_time.'%');
            })
            ->when($inventor, function ($query) use ($inventor) {
                return $query->where('product.inventor',$inventor);
            })
            ->get();
        $second_type = object_to_array(
            DB::table('second_type')->where(array("first_type_id" => $this->patent))->
            get(['id', 'name'])
        );
        $progress = $this->getProgress($this->patent);
        $data = ['patent', 'second_type', 'progress','keywords'];
        return view('user/mine/myPatentSearch', compact($data));
    }

    public function addMyPatent()
    {
        $uid = Session::get('uid');
        $input = Request::all();
        $data['user_id'] = $uid;
        $data['number'] = $input['patent_num'];
        $data['name'] = $input['patent_name'];
        $data['updated_at'] = date('Y-m-d h:i:s');
        $data['level'] = 0;
        $data['applicant'] = $input['patent_first_apply'];
        $data['inventor'] = $input['inventor'];
        $data['first_type_id'] = $this->patent;
        $data['second_type_id'] = $input['patent_type'];
        $data['is_upload_notice'] = 0;
        $data['authority_time'] = $input['authorization_date'];
        $data['created_at'] = $input['apply_date'];
        $data['phone'] = $input['phone'];
        $data['company'] = $input['patent_company'];
        $data['is_download_notice'] = 1;
        if (!empty($data)) {
            $res = DB::table('product')->insert($data);
            if ($res) {
                return back()->with('success', '成功添加专利');
            } else {
                return back()->with('error', '添加专利失败');
            }
        } else {
            return back()->with('error', '数据传输错误，请联系管理员');
        }
//       dump($data);exit();
    }

    /**
     * 统一的删除接口
     * @param $id  int 产品id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function delProduct($id)
    {

        if (!empty($id)) {
//            DB::beginTransaction();
             try{
                 $res = DB::table('product')->where(array("id" => $id))->first();
                 $ids = DB::table('progress')->where(array('product_id' => $id))->pluck('id');
                 $ids_opration = DB::table('operation')->where(array('product_id' => $id))->pluck('id');
                 $ids_file = DB::table('files')->where(array('product_id' => $id))->pluck('id');

                 $res=collect($res)->toArray();
                 $ids=collect($ids)->toArray();
                 $ids_opration=collect($ids_opration)->toArray();
                 $ids_file=collect($ids_file)->toArray();

                  if (!empty($res)) {
                      $res1=  Product::destroy($id);
                      // dump($res1);die();
                  }
                 if (!empty($ids)) {
                     Progress::destroy($ids);
                     $opp=DB::table('progress_operator_relation')->whereIn("progress_id",$ids)->pluck('id');
                     $opp=collect($opp)->toArray();
                     if(!empty($opp)){
                         ProgressOperatorRelation::destroy($opp);
                     }
                  // dump($res);die();
                 }
                 if (!empty($ids_opration)) {
                     Operation::destroy($ids_opration);

                 }
                 if (!empty($ids_file)) {
                     Files::destroy($ids_file);
                 }
                 if ($res) {
                     return back()->with('success', '删除成功');
                 } else {
                     return back()->with('error', '删除失败');
                 }
                 DB::commit();
             } catch(\Exception $e){
                 DB::callback();
                 return back()->with('error',$e->getMessage() );
             }
        }else {
            return back()->with('error', '数据传输错误，请联系管理员');
        }
    }

    public function myTrademark()
    {
        $uid = Session::get('uid');
        /*$trademark = object_to_array(
            DB::table('product')->
            where(array("product.user_id" => $uid, 'product.first_type_id' => 2))->
            join('second_type', 'product.second_type_id', '=', 'second_type.id')->
            leftJoin('progress', 'product.id', '=', 'progress.product_id')->
            leftJoin('progress_list', 'progress.progress_list_id', '=', 'progress_list.id')->
            get(['product.id', 'product.applicant', 'second_type.name as second_type',
                'product.number', 'product.name', 'product.registration_time',
                'product.authority_time', 'product.quoter',
                'progress_list.name as progress_type', 'product.file'])
        );*/
        $product = Product::with(['Progress' => function ($query) {
            $query->orderBy('created_at', 'ASC');
        }, 'SecondType', 'FirstType','Files'])
            ->where(['user_id' => $uid])
            ->where(['first_type_id' => $this->trademark])
            ->paginate($this->pageNum);
        $progress = $this->getProgress($this->trademark);
        $second_type = object_to_array(
            DB::table('second_type')->where(array("first_type_id" => $this->trademark))->
            get(['id', 'name'])
        );
        //collect();
        /* $data = [
             'trademark' => $trademark,
             'second_type' => $second_type
         ];*/
//        dump($data['trademark']);exit();
        // dump($product);exit;
//统计个数
        $count = [0, 0, 0, 0];
        $count[0]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 4],
            ])->count();
        $count[1]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 5],
            ])->count();
        $count[2]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 6],
            ])->count();
        $count[3]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 7],
            ])->count();
       // dd($count);
        $data = ['product', 'second_type', 'progress','count'];
        /* dump($progress);
         dump($product);
         exit;*/
        return view('user/mine/myTrademark', compact($data));
    }
//
//    public function myTrademarkSearch()
//    {
//        $uid = Session::get('uid');
//        $request = Request::all();
//        $keywords="";
//        if (isset($request['search'])) {
//            $keywords = $request['search'];
//        }
//        $product = Product::with(['Progress' => function ($query) {
//            $query->orderBy('created_at', 'ASC');
//        }, 'SecondType', 'FirstType','Files'])
//            ->where(['user_id' => $uid])
//            ->where(['first_type_id' => $this->trademark])
//            ->get();
//        $progress = $this->getProgress($this->trademark);
//        $second_type = object_to_array(
//            DB::table('second_type')->where(array("first_type_id" => $this->trademark))->
//            get(['id', 'name'])
//        );
//        $data = ['product', 'second_type', 'progress','keywords'];
//        return view('user/mine/myTrademarkSearch', compact($data));
//    }

    public function myTrademarkCertain()
    {
        $uid = Session::get('uid');
        $applicant = Request::input('applicant');
        $company = Request::input('company');
        $second_type = Request::input('second_type');
        $number = Request::input('number');
        $product_name = Request::input('product_name');
        $created_at = Request::input('created_at');
        $authority_time = Request::input('authority_time');
        //dd($request);
        $product = Product::with(['Progress' => function ($query) {
            $query->orderBy('created_at', 'ASC');
        }, 'SecondType', 'FirstType','Files'])
            ->where([
                ['user_id','=',$uid],
                ['first_type_id','=',$this->trademark],
            ])
            ->when($applicant, function ($query) use ($applicant) {
                return $query->where('product.applicant', $applicant);
            })
            ->when($company, function ($query) use ($company) {
                return $query->where('product.company', $company);
            })
            ->when($second_type, function ($query) use ($second_type) {
                return $query->where('product.second_type_id', $second_type);
            })
            ->when($number, function ($query) use ($number) {
                return $query->where('product.number', $number);
            })
            ->when($product_name, function ($query) use ($product_name) {
                return $query->where('product.name', $product_name);
            })
            ->when($created_at, function ($query) use ($created_at) {
                return $query->where('product.created_at','like', '%'.$created_at.'%');
            })
            ->when($authority_time, function ($query) use ($authority_time) {
                return $query->where('product.authority_time','like', '%'.$authority_time.'%');
            })
            ->get();
        //dd($product);
        $progress = $this->getProgress($this->trademark);
        $second_type = object_to_array(
            DB::table('second_type')->where(array("first_type_id" => $this->trademark))->
            get(['id', 'name'])
        );
        $data = ['product', 'second_type', 'progress'];
        return view('user/mine/myTrademarkSearch', compact($data));
    }

    public function addMyTrademark()
    {
        $uid = Session::get('uid');
        $input = Request::all();
        $data['user_id'] = $uid;
        $data['number'] = $input['trademark_num'];
        $data['name'] = $input['trademark_name'];
        $data['updated_at'] = date('Y-m-d h:i:s');
        $data['level'] = 0;
        $data['applicant'] = $input['trademark_apply_person'];
        $data['first_type_id'] = $this->trademark;
        $data['second_type_id'] = $input['trademark_type'];
        $data['is_upload_notice'] = 0;
        $data['authority_time'] = $input['trademark_authorization_date'];
        $data['created_at'] = $input['trademark_apply_date'];
        $data['phone'] = $input['phone'];
        $data['company'] = $input['trademark_company'];
        $data['is_download_notice'] = 1;
//        dump($data);exit();
        if (!empty($data)) {
            $res = DB::table('product')->insert($data);
            if ($res) {
                return back()->with('success', '添加成功');
            } else {
                return back()->with('error', '添加失败');
            }
        } else {
            return back()->with('error', '数据传输错误，请联系管理员');
        }
    }


    public function myCopyright()
    {
        $uid = Session::get('uid');
        /*  $copyright = object_to_array(
              DB::table('product')->
              where(array("product.user_id" => $uid, 'product.first_type_id' => 3))->
              join('second_type', 'product.second_type_id', '=', 'second_type.id')->
              leftJoin('progress', 'product.id', '=', 'progress.product_id')->
              leftJoin('progress_list', 'progress.progress_list_id', '=', 'progress_list.id')->
              get(['product.id', 'product.applicant', 'second_type.name as second_type',
                  'product.number', 'product.name', 'product.registration_time',
                  'product.authority_time', 'product.quoter',
                  'progress_list.name as progress_type', 'product.file'])
          );*/
        $product = Product::with(['Progress' => function ($query) {
            $query->orderBy('created_at', 'ASC');
        }, 'SecondType', 'FirstType','Files'])
            ->where(['user_id' => $uid])
            ->where(['first_type_id' => $this->copyright])
            ->paginate($this->pageNum);
        $progress = $this->getProgress($this->copyright);
        $second_type = object_to_array(
            DB::table('second_type')->where(array("first_type_id" => $this->copyright))->
            get(['id', 'name'])
        );
//        dump($copyright);exit();
        /* $data = [
             'copyright' => $copyright,
             'second_type' => $second_type
         ];*/
        /* dump($product);
         dump($progress);
         exit();*/
//统计个数
        $count = [0, 0];
        $count[0]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 8],
            ])->count();
        $count[1]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 9],
            ])->count();

        $data = ['product', 'second_type', 'progress','count'];
        return view('user/mine/myCopyright', compact($data));
    }
//    public function myCopyrightSearch(){
//        $uid = Session::get('uid');
//        $request = Request::all();
//        $keywords="";
//        if (isset($request['search'])) {
//            $keywords = $request['search'];
//        }
//        $product = Product::with(['Progress' => function ($query) {
//            $query->orderBy('created_at', 'ASC');
//        }, 'SecondType', 'FirstType','Files'])
//            ->where(['user_id' => $uid])
//            ->where(['first_type_id' => $this->copyright])
//            ->get();
//        $progress = $this->getProgress($this->copyright);
//        $second_type = object_to_array(
//            DB::table('second_type')->where(array("first_type_id" => $this->copyright))->
//            get(['id', 'name'])
//        );
//        $data = ['product', 'second_type', 'progress','keywords'];
//        return view('user/mine/myCopyrightSearch', compact($data));
//    }

    public function myCopyrightCertain()
    {
        $uid = Session::get('uid');
        $applicant = Request::input('applicant');
        $company = Request::input('company');
        $second_type = Request::input('second_type');
        $number = Request::input('number');
        $product_name = Request::input('product_name');
        $created_at = Request::input('created_at');
        $authority_time = Request::input('authority_time');
        //dd($request);
        $product = Product::with(['Progress' => function ($query) {
            $query->orderBy('created_at', 'ASC');
        }, 'SecondType', 'FirstType','Files'])
            ->where([
                ['user_id','=',$uid],
                ['first_type_id','=',$this->copyright],
            ])
            ->when($applicant, function ($query) use ($applicant) {
                return $query->where('product.applicant', $applicant);
            })
            ->when($company, function ($query) use ($company) {
                return $query->where('product.company', $company);
            })
            ->when($second_type, function ($query) use ($second_type) {
                return $query->where('product.second_type_id', $second_type);
            })
            ->when($number, function ($query) use ($number) {
                return $query->where('product.number', $number);
            })
            ->when($product_name, function ($query) use ($product_name) {
                return $query->where('product.name', $product_name);
            })
            ->when($created_at, function ($query) use ($created_at) {
                return $query->where('product.created_at','like', '%'.$created_at.'%');
            })
            ->when($authority_time, function ($query) use ($authority_time) {
                return $query->where('product.authority_time','like', '%'.$authority_time.'%');
            })
            ->get();
        //dd($product);
        $progress = $this->getProgress($this->copyright);
        $second_type = object_to_array(
            DB::table('second_type')->where(array("first_type_id" => $this->copyright))->
            get(['id', 'name'])
        );
        $data = ['product', 'second_type', 'progress'];
        return view('user/mine/myCopyrightSearch', compact($data));
    }
    public function addMyCopyright()
    {
        $uid = Session::get('uid');
        $input = Request::all();
        $data['user_id'] = $uid;
        $data['number'] = $input['copyright_num'];
        $data['name'] = $input['copyright_name'];
        $data['updated_at'] = date('Y-m-d h:i:s');
        $data['applicant'] = $input['apply_person'];
        $data['first_type_id'] = $this->copyright;
        $data['second_type_id'] = $input['copyright_type'];
        $data['is_upload_notice'] = 0;
        $data['authority_time'] = $input['authorization_date'];
        $data['created_at'] = $input['apply_date'];
        $data['phone'] = $input['phone'];
        $data['company'] = $input['company_'];
        $data['is_download_notice'] = 1;
        if (!empty($data)) {
            $res = DB::table('product')->insert($data);
            if ($res) {
                return back()->with('success', '添加成功');
            } else {
                return back()->with('error', '添加失败');
            }
        } else {
            return back()->with('error', '数据传输失败,请联系管理员');
        }
    }

    public function delMyCopyright($id)
    {
//        dump($id);exit();
        if (!empty($id)) {
            $res = DB::table('product')->where(array("id" => $id))->delete();
            if ($res) {
                return back()->with('success', '删除成功');
            } else {
                return back()->with('error', '删除失败');
            }
        } else {
            return back()->with('error', '数据传输失败，请联系管理员');
        }
    }

    public function myProject()
    {
        $uid = Session::get('uid');
        /* $project = object_to_array(
             DB::table('product')->
             where(array("product.user_id" => $uid, 'product.first_type_id' => 4))->
             join('second_type', 'product.second_type_id', '=', 'second_type.id')->
             leftJoin('progress', 'product.id', '=', 'progress.product_id')->
             leftJoin('progress_list', 'progress.progress_list_id', '=', 'progress_list.id')->
             get(['product.id', 'product.applicant', 'second_type.name as second_type',
                 'product.name', 'product.registration_time', 'product.registration_area',
                 'product.authority_time', 'progress_list.name as progress_type', 'product.file'])
         );*/
        $product = Product::with(['Progress' => function ($query) {
            $query->orderBy('created_at', 'ASC');
        }, 'SecondType', 'FirstType','Files'])
            ->where(['user_id' => $uid])
            ->where(['first_type_id' => $this->project])
            ->paginate($this->pageNum);
        $progress = $this->getProgress($this->project);
        $second_type = object_to_array(
            DB::table('second_type')->where(array("first_type_id" => $this->project))->
            get(['id', 'name'])
        );
//        dump($project);exit();
        /*$data = [
            'project' => $project,
            'second_type' => $second_type
        ];*/
        // dump($product);exit;
        //统计
        $count = [0, 0,0,0,0,0];
        $count[0]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 10],
            ])->count();
        $count[1]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 11],
            ])->count();
        $count[2]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 12],
            ])->count();
        $count[3]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 13],
            ])->count();
        $count[4]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 14],
            ])->count();
        $count[5]=DB::table('product')
            ->where([
                ['user_id', '=', $uid],
                ['second_type_id', '=', 15],
            ])->count();

        $data = ['product', 'second_type', 'progress','count'];
        return view('user/mine/myProject', compact($data));
    }
//    public function myProjectSearch(){
//        $uid = Session::get('uid');
//        $request = Request::all();
//        $keywords="";
//        if (isset($request['search'])) {
//            $keywords = $request['search'];
//        }
//        $product = Product::with(['Progress' => function ($query) {
//            $query->orderBy('created_at', 'ASC');
//        }, 'SecondType', 'FirstType','Files'])
//            ->where(['user_id' => $uid])
//            ->where(['first_type_id' => $this->project])
//            ->get();
//        $progress = $this->getProgress($this->project);
//        $second_type = object_to_array(
//            DB::table('second_type')->where(array("first_type_id" => $this->project))->
//            get(['id', 'name'])
//        );
//        $data = ['product', 'second_type', 'progress','keywords'];
//        return view('user/mine/myProjectSearch', compact($data));
//    }

    public function myProjectCertain()
    {
        $uid = Session::get('uid');
        $applicant = Request::input('applicant');
        $company = Request::input('company');
        $second_type = Request::input('second_type');
        $registration_time = Request::input('registration_time');
        $registration_area = Request::input('registration_area');
        $created_at = Request::input('created_at');
        $authority_time = Request::input('authority_time');
        $product = Product::with(['Progress' => function ($query) {
            $query->orderBy('created_at', 'ASC');
        }, 'SecondType', 'FirstType','Files'])
            ->where([
                ['user_id','=',$uid],
                ['first_type_id','=',$this->project],
            ])
            ->when($applicant, function ($query) use ($applicant) {
                return $query->where('product.applicant', $applicant);
            })
            ->when($company, function ($query) use ($company) {
                return $query->where('product.company', $company);
            })
            ->when($second_type, function ($query) use ($second_type) {
                return $query->where('product.second_type_id', $second_type);
            })
            ->when($registration_time, function ($query) use ($registration_time) {
                return $query->where('product.registration_time','like', '%'.$registration_time.'%');
            })
            ->when($registration_area, function ($query) use ($registration_area) {
                return $query->where('product.registration_area', $registration_area);
            })
            ->when($created_at, function ($query) use ($created_at) {
                return $query->where('product.created_at','like', '%'.$created_at.'%');
            })
            ->when($authority_time, function ($query) use ($authority_time) {
                return $query->where('product.authority_time','like', '%'.$authority_time.'%');
            })
            ->get();
        $progress = $this->getProgress($this->project);
        $second_type = object_to_array(
            DB::table('second_type')->where(array("first_type_id" => $this->project))->
            get(['id', 'name'])
        );
        $data = ['product', 'second_type', 'progress'];
        return view('user/mine/myProjectSearch', compact($data));
    }
    public function delMyProject($id)
    {
        if (!empty($id)) {
            $res = DB::table('product')->where(array("id" => $id))->delete();
            if ($res) {
                return back()->with('success', '删除成功');
            } else {
                return back()->with('error', '删除失败');
            }
        } else {
            return back()->with('error', '数据传输失败，请联系管理员');
        }
    }

    public function addMyProject()
    {
        $uid = Session::get('uid');
        $input = Request::all();
//        dump($input);exit();
        $data['user_id'] = $uid;
        $data['name'] = $input['project_name'];
        $data['updated_at'] = date('Y-m-d h:i:s');
        $data['level'] = 0;
        $data['applicant'] = $input['apply_person'];
        $data['first_type_id'] = $this->project;
        $data['second_type_id'] = $input['project_type'];
        $data['is_upload_notice'] = 0;
        $data['authority_time'] = $input['authorization_date'];
        $data['registration_time'] = $input['company_create_at'];
        $data['created_at'] = $input['created_at'];
        $data['phone'] = $input['phone'];
        $data['company'] = $input['company_'];
        $data['is_download_notice'] = 1;
        //dump($data);exit;
        if (!empty($data)) {
            $res = DB::table('product')->insert($data);
            if ($res) {
                return back()->with('success', '添加成功');
            } else {
                return back()->with('error', '添加失败');
            }
        } else {
            return back()->with('error', '数据传输失败,请联系管理员');
        }
    }

    /**
     * 申请纸质通知书
     * @return \Illuminate\Http\RedirectResponse|string
     */
    public function applyNotice()
    {
        $request = Request::all();
        $id = $request['p'];
        $pid = $request['pro'];
        //dump($request);exit;
        $item = Product::find($id);
        $item1 = Progress::with(['ProgressList'])->find($pid);

        // dump($item1);exit;
        if (empty($item)) {
            return back()->with('error', '没有该条数据');
        }
        $user = User::find($item['user_id']);
        if (empty($item1) || empty($user)) {
            return error_return("不能申请纸质通知书");
        }
        if (!isset($request['address'])) {
            if (empty($user['address']))
                return error_return('地址不能为空');
        } else {
            $user['address'] = $request['address'];
        }
        if ($item1['is_cancel'] == config('config.mission_state_map.cancel')) {
            //  return back()->with('error',"任务已被取消，不能申请纸质通知书");
            return error_return("任务已被取消，不能申请纸质通知书");
        }
        if ($item1['ProgressList']['progress_state'] == 0) {
            return error_return("业务还未办理成功，不能申请通知书");
        }
        $item['is_download_notice'] = 3;
        if ($item->save() && $item1->save() && $user->save()) {
            return back()->with('success', '申请成功');
        } else {
            return back()->with('error', '申请失败');
        }
    }

    /**
     * 续费
     * @return \Illuminate\Http\RedirectResponse
     */
    public function renew()
    {
        $request = Request::all();
        $id = $request['product'];
        $item = Product::find($id);
        $date = date('Y-m-d H:i:s');
        $uid = Session::get('uid');
        if (empty($item)) {
            return error_return("暂无数据");
        }
        //dump($item);exit;
        $prog=Progress::where(['product_id'=>$id])
            ->orderBy('created_at','desc')
            ->get();
        if($prog->isNotEmpty()){
            $arr=$prog->toArray();
            $ite=$arr[0];
            if($ite['state']!=3&&$ite['state']!=4)
            {
                return error_return("任务还未办理成功，不能申请续费");
            }
        }
        $item['authority_time']=null;
        $operation['product_id'] = $id;
        $operation['operator_id'] = $uid;
        $operation['operator_type'] = config('config.operation_role.user');
        $operation['content'] = '申请续费';
        $operation['operator_name'] = '用户-' . Session::get('username');
        $progress['progress_list_id'] = ProgressList::where(['second_type_id' => $item['second_type_id']])
            ->first()
            ->getKey();
        $progress['product_id'] = $id;
        $progress['claim_state'] = config('config.claim_state.init');
        $progress['created_at'] = $date;
        $progress['updated_at'] = $date;
        $progress['first_type_id'] = $item['first_type_id'];
        $progress['second_type_id'] = $item['second_type_id'];
        $progress['user_id'] = $uid;
        $progress['is_renew'] = 1;
        $progress['order'] = createdNumber();
        $item['is_download_notice'] = 1;
        $pro = Progress::create($progress);
        if ($pro->save() && addOperation($operation) && $item->save()) {
            return success_return("续费申请成功");
        } else {
            return error_return("续费申请失败");
        }
    }

    /**
     * 上传报件资料
     * @return \Illuminate\Http\RedirectResponse
     */
    public function uploadReport(){
        $uid=Session::get('uid');
        if(empty($uid)){
            return Redirect::to('/');
        }
        $path='Uploads/resources/';
        $dir = md5($uid).'/';
        $request=Request::all();
        $id=$request['upload-pro'];
        $filename=upload($path.$dir);
        $item=Product::find($id);
        if (!empty($item)){
            if(is_file($path.$item['file'])){
                    unlink($path.$item['file']);
            }
        }else{
            return error_return("没有该条数据");
        }
        if(!empty($filename)){
            $item['file']=$dir.$filename;
        }else{
            return error_return('上传失败');
        }
        $item['updated_at']=date('Y-m-d H:i:s');
        if($item->save()){
            return success_return("上传成功");
        }else{
            return error_return("上传失败");
        }
    }
    public function uploadOfficeFile()
    {
        $uid=Session::get('uid');
        if(empty($uid)){
            return Redirect::to('/');
        }
        $path='Uploads/resources/';
        $request=Request::all();
       // dd($request);
        $id=$request['office-pid'];
        $dir = md5($uid).'/officerFile/'.md5($id).'/';
       // dump($id);exit;
        $filename=upload($path.$dir);
        $date = date('Y-m-d H:i:s');
        if(empty($filename)){
            return error_return("上传失败");
        }
        $item=Product::find($id);
        if (empty($item)){
            return error_return("没有该条数据");
        }
        if($item['is_download_notice']==0){
            $item['is_download_notice']=1;
        }
        $item['updated_at']=$date;
        $params['url']=$dir.$filename;
        $params['created_at']=$date;
        $params['updated_at']=$date;
        $params['product_id']=$id;
        $params['name']=$request['filename'];
        $f = Files::create($params);
        if($f->save()&&$item->save()){
            return success_return("上传成功");
        }else{
            return error_return("上传失败");
        }
    }
    /**
     * 文件压缩打包下载
     * @return string
     */
    public function ajxZip()
    {
        $request=Request::all();
//        dd($request);
        $pid=$request['id'];
        return json_return(zipDownloads(Session::get('uid'),$pid));
    }
    /**
     * 读取excel数据 导入专利
     */
    public function readPatentExcel()
    {
        $data = [];
        $dir = 'Uploads/file/patent/';
        $file = Input::file('file');
        $filename = time() . '_' . mt_rand() . "." . $file->getClientOriginalExtension();
        if (!$file->move($dir, $filename)) {
            return back()->with('error', '导入失败');
        }
        $filePath = $dir . $filename;
        $add = [];
        $format = "Y-m-d H:i:s";
        $item = [];
        $data=$this->getExcelData($filePath);
        $userId = Session::get('uid');
        $now = date($format);
        $secondIds = ota(DB::table($this->second_type_table)
            ->where(['first_type_id' => $this->patent])
            ->pluck('id'));
        foreach ($data as $key => $obj) {
            if ($key == 4) {
                if ($data[$key][0] != 'lemner') {
                    $item['user_id'] = $userId;
                    $item['number'] = $obj[1];
                    $item['name'] = $obj[0];
                    $item['level'] = 0;
                    $item['updated_at'] = $now;
                    $item['created_at'] = $now;
                    $item['applicant'] = $obj[2];
                    $item['inventor'] = $obj[6];
                    $item['phone'] = $obj[7];
                    $item['first_type_id'] = $this->patent;
                    $index = (int)$obj[3] - 1;
                    if (isset($secondIds[$index])) {
                        $item['second_type_id'] = $secondIds[$index];
                    } else {
                        return error_return("类型不合法");
                    }
                    if ($this->checkDateIsValid($obj[4]) && $this->checkDateIsValid($obj[5])) {
                        $item['created_at'] = $obj[4];
                        $item['authority_time'] = $obj[5];
                    } else {
                        return error_return("日期数据不合法");
                    }
                    $add[] = $item;
                }
            }
            if ($key > 4) {
                $item['user_id'] = $userId;
                $item['number'] = $obj[1];
                $item['name'] = $obj[0];
                $item['level'] = 0;
                $item['updated_at'] = $now;
                $item['applicant'] = $obj[2];
                $item['inventor'] = $obj[6];
                $item['phone'] = $obj[7];
                $item['first_type_id'] = $this->patent;
                $index = (int)$obj[3] - 1;
                if (isset($secondIds[$index])) {
                    $item['second_type_id'] = $secondIds[$index];
                } else {
                    return error_return("类型不合法");
                }
                if ($this->checkDateIsValid($obj[4]) && $this->checkDateIsValid($obj[5])) {
                    $item['created_at'] = $obj[4];
                    $item['authority_time'] = $obj[5];
                } else {
                    return error_return("日期数据不合法");
                }
                $add[] = $item;
            }
        }
        DB::table($this->product_table)->insert($add);
        return success_return("导入成功");
    }

    /**
     * 读取excel数据 导入项目
     */
    public function readProjectExcel()
    {
        $data = [];
        $dir = 'Uploads/file/project/';
        $file = Input::file('file');
        $filename = time() . '_' . mt_rand() . "." . $file->getClientOriginalExtension();
        if (!$file->move($dir, $filename)) {
            return back()->with('error', '导入失败');
        }
        $filePath = $dir . $filename;
        $add = [];
        $data=$this->getExcelData($filePath);
        $format = "Y-m-d H:i:s";
        $item = [];
        $userId = Session::get('uid');
        $now = date($format);
        $secondIds = ota(DB::table($this->second_type_table)
            ->where(['first_type_id' => $this->project])
            ->pluck('id'));
        foreach ($data as $key => $obj) {
            if ($key == 4) {
                if ($data[$key][0] != 'lemner') {
                    $item['user_id'] = $userId;
                    $item['name'] = $obj[0];
                    $item['level'] = 0;
                    $item['updated_at'] = $now;
                    $item['applicant'] = $obj[2];
                    $item['registration_area'] = $obj[3];
                    $item['phone'] = $obj[7];
                    $item['first_type_id'] = $this->project;
                    $index = (int)$obj[1] - 1;

                    if (isset($secondIds[$index])) {
                        $item['second_type_id'] = $secondIds[$index];
                    } else {
                        return error_return("类型不合法");
                    }
                    if ($this->checkDateIsValid($obj[5]) && $this->checkDateIsValid($obj[4]) && $this->checkDateIsValid($obj[6])) {
                        $item['authority_time'] = $obj[5];
                        $item['registration_time'] = $obj[4];
                        $item['created_at'] = $obj[6];
                    } else {
                        return error_return("日期数据不合法");
                    }
                    $add[] = $item;
                }
            }
            if ($key > 4) {
                $item['user_id'] = $userId;
                $item['number'] = $obj[0];
                $item['level'] = 0;
                $item['updated_at'] = $now;
                $item['applicant'] = $obj[2];
                $item['registration_area'] = $obj[3];
                $item['first_type_id'] = $this->project;
                $item['phone'] = $obj[7];
                $index = (int)$obj[1] - 1;
                if (isset($secondIds[$index])) {
                    $item['second_type_id'] = $secondIds[$index];
                } else {
                    return error_return("类型不合法");
                }
                if ($this->checkDateIsValid($obj[5]) && $this->checkDateIsValid($obj[4]) && $this->checkDateIsValid($obj[6])) {
                    $item['authority_time'] = $obj[5];
                    $item['registration_time'] = $obj[4];
                    $item['created_at'] = $obj[6];
                } else {

                    return error_return("日期数据不合法");
                }
                $add[] = $item;
            }
        }
        DB::table($this->product_table)->insert($add);
        return success_return("导入成功");
    }

    /**
     * 读取excel数据 导入版权
     */
    public function readCopyrightExcel()
    {
        $dir = 'Uploads/file/copyright/';
        $file = Input::file('file');
        $filename = time() . '_' . mt_rand() . "." . $file->getClientOriginalExtension();
        if (!$file->move($dir, $filename)) {
            return back()->with('error', '导入失败');
        }
        $filePath = $dir . $filename;
        $add = [];
        $data=$this->getExcelData($filePath);
        $format = "Y-m-d H:i:s";
        $item = [];
        $userId = Session::get('uid');
        $now = date($format);
        $secondIds = ota(DB::table($this->second_type_table)
            ->where(['first_type_id' => $this->copyright])
            ->pluck('id'));
        foreach ($data as $key => $obj) {
            if ($key == 4) {
                if ($data[$key][0] != 'lemner') {
                    $item['user_id'] = $userId;
                    $item['number'] = $obj[1];
                    $item['name'] = $obj[0];
                    $item['level'] = 0;
                    $item['updated_at'] = $now;
                    $item['applicant'] = $obj[2];
                    $item['first_type_id'] = $this->copyright;
                    $item['phone'] = $obj[6];
                    $index = (int)$obj[3] - 1;
                    if (isset($secondIds[$index])) {
                        $item['second_type_id'] = $secondIds[$index];
                    } else {
                        return error_return("类型不合法");
                    }
                    if ($this->checkDateIsValid($obj[4]) && $this->checkDateIsValid($obj[5])) {
                        $item['authority_time'] = $obj[5];
                        $item['created_at'] = $obj[4];
                    } else {
                        return error_return("日期数据不合法");
                    }
                    $add[] = $item;
                }
            }
            if ($key > 4) {
                $item['user_id'] = $userId;
                $item['number'] = $obj[1];
                $item['name'] = $obj[0];
                $item['level'] = 0;
                $item['updated_at'] = $now;
                $item['created_at'] = $now;
                $item['applicant'] = $obj[2];
                $item['first_type_id'] = $this->copyright;
                $item['phone'] = $obj[6];
                $index = (int)$obj[3] - 1;
                if (isset($secondIds[$index])) {
                    $item['second_type_id'] = $secondIds[$index];
                } else {
                    return error_return("类型不合法");
                }
                if ($this->checkDateIsValid($obj[4]) && $this->checkDateIsValid($obj[5])) {
                    $item['authority_time'] = $obj[5];
                    $item['created_at'] = $obj[4];
                } else {
                    return error_return("日期数据不合法");
                }
                $add[] = $item;
            }
        }
        DB::table($this->product_table)->insert($add);
        return success_return("导入成功");
    }


    /**
     * 读取excel数据 导入商标
     */
    public function readTrademarkExcel()
    {
        $data = [];
        $dir = 'Uploads/file/trademark/';
        $file = Input::file('file');
        $filename = time() . '_' . mt_rand() . "." . $file->getClientOriginalExtension();
        if (!$file->move($dir, $filename)) {
            return back()->with('error', '导入失败');
        }
        $filePath = $dir . $filename;
        $add = [];
        $data=$this->getExcelData($filePath);
        $format = "Y-m-d H:i:s";
        $item = [];
        $userId = Session::get('uid');
        $now = date($format);
        $secondIds = ota(DB::table($this->second_type_table)
            ->where(['first_type_id' => $this->trademark])
            ->pluck('id'));
        foreach ($data as $key => $obj) {
            if ($key == 4) {
                if ($data[$key][0] != 'lemner') {
                    $item['user_id'] = $userId;
                    $item['number'] = $obj[1];
                    $item['name'] = $obj[0];
                    $item['level'] = 0;
                    $item['updated_at'] = $now;
                    $item['applicant'] = $obj[2];
                    $item['phone'] = $obj[6];
                    $item['first_type_id'] = $this->trademark;
                    $index = (int)$obj[3] - 1;
                    if (isset($secondIds[$index])) {
                        $item['second_type_id'] = $secondIds[$index];
                    } else {
                        return error_return("类型不合法");
                    }
                    if ($this->checkDateIsValid($obj[4]) && $this->checkDateIsValid($obj[5])) {
                        $item['authority_time'] = $obj[4];
                        $item['created_at'] = $obj[5];
                    } else {
                        return error_return("日期数据不合法");
                    }
                    $add[] = $item;
                }
            }
            if ($key > 4) {
                $item['user_id'] = $userId;
                $item['number'] = $obj[1];
                $item['name'] = $obj[0];
                $item['level'] = 0;
                $item['updated_at'] = $now;
                $item['applicant'] = $obj[2];
                $item['first_type_id'] = $this->trademark;
                $item['phone'] = $obj[6];
                $index = (int)$obj[3] - 1;
                if (isset($secondIds[$index])) {
                    $item['second_type_id'] = $secondIds[$index];
                } else {
                    return error_return("类型不合法");
                }
                if ($this->checkDateIsValid($obj[4]) && $this->checkDateIsValid($obj[5])) {
                    $item['authority_time'] = $obj[4];
                    $item['created_at'] = $obj[5];

                } else {
                    return error_return("日期数据不合法");
                }
                $add[] = $item;
            }
        }
        DB::table($this->product_table)->insert($add);
        return success_return("导入成功");
    }

    /**
     * 校验日期格式是否正确
     *
     * @param string $date 日期
     * @param string $formats 需要检验的格式数组
     * @return boolean
     */
    function checkDateIsValid($date, $formats = "Y-m-d H:i:s")
    {
        $unixTime = strtotime($date);
        if (!$unixTime) { //strtotime转换不对，日期格式显然不对。
            return false;
        }
        //校验日期的有效性，只要满足其中一个格式就OK
        if (date($formats, $unixTime) == $date) {
            return true;
        }
        return false;
    }

    public function getProgress($id)
    {
        $p = ota(FirstType::with(['ProgressList'])
            ->where(['id' => $id])
            ->first());//获取progressList表中id=1的并转换为数组
        $progress = [];
        foreach ($p['progress_list'] as $k => $v) {
            $item = [];
            $item['name'] = $v['name'];
            $item['flag'] = $v['progress_state'];
            $progress[$v['id']] = $item;
        }
        return $progress;
    }
    function getExcelData($filePath)
    {
        $res=[];
        Excel::load($filePath,function ($reader)use(&$res){
            $reader->setDateFormat('Y-m-d H:i:s');
            $reader->ignoreEmpty();
            //获取表中的数据
            $res = $reader->all()->toArray();
        });
        return $res;
    }

    public function yes()
    {
//        DB::connection()->enableQueryLog(); // 开启查询日志
        $fileid=request::all();
        $sql=Db::table('files')
            ->where('id',$fileid)
            ->update(['yn'=>1]);
//        $queries = DB::getQueryLog(); // 获取查询日志
//        print_r($queries); // 即可查看执行的sql，传入的参数等等
        //dd($sql);
            return json_encode($sql);
    }
}